<?php

namespace App\Services;

use App\Models\Order;
use App\Models\OrderLease;
class CreditService
{
    //新征信接口2022-11-18
    //是否查询成功
    const RESULT_SUCCESS = 1; //成功
    const RESULT_FAIL = 2; //失败
    const RESULT_ING = 3; //请求中

    /**
     * 获取征信结果
     */
    static public function getInvestData($input){
        // $key = "67333FCC2FA244F8BEE4613AC18CD845";   //密钥-测试环境
        $key = "81A2F363DC5D4429BB6A0B8DFDD95C3E";   //密钥-正式环境

        // $url = "https://server.junxinhengyi.cn:16633/api/guarantee/query"; //测试
        $url = "https://serice.junxinhengyi.cn:4433/api/guarantee/query"; //线上

        $name = $input['cert_name'];   //姓名
        $number = $input['cert_no'];   //身份证号
        $phone = $input['mobile'];   //手机号
        $order_no = $input['trade_no'];   //手机号


        self::login("rarmwl", "rarmwl@2023#03.10@",'https://img.qianbaozuji.com/'.$input['idcard_front'],'/2023/'.$input['idcard_front']);

        self::login("rarmwl", "rarmwl@2023#03.10@",'https://img.qianbaozuji.com/'.$input['idcard_back'],'/2023/'.$input['idcard_back']);


        $ident_image_front = '/2023/'.$input['idcard_front'];

        $ident_image_back = '/2023/'.$input['idcard_back'];

        $flow_id_2 = Order::where('id',$input['id'])->value('flow_id_2');

        self::login("rarmwl", "rarmwl@2023#03.10@",'https://img.qianbaozuji.com/'.$flow_id_2.'.pdf','/2023/'.$flow_id_2.'.pdf');

        $grant_image = '/2023/'.$flow_id_2.'.pdf';

        $requestId = $order_no.mt_rand(1000,9999).mt_rand(1000,9999);

        $scoreNo = $order_no.mt_rand(1000,9999).mt_rand(1000,9999);
        // dd($name);
        $user = array(
            'requestId'=>$requestId, //请求流水号，单次http请求唯一
            'scoreNo'=>$scoreNo, // 请求编号
            // 'productType'=>"3",//产品信息-测试
            'productType'=>"7",//产品信息-正式
            'name' => $name,
            'phone' => $phone,
            'idcardNumber' => $number,
            'urlStr1' => $ident_image_front, //身份证正面，传/YYYY/MM/DD/文件名.后缀
            'urlStr2' => $ident_image_back, //身份证反面，传/YYYY/MM/DD/文件名.后缀
            'grantAuthorizationUrl' => $grant_image, //授权书BASE64字符串
            'grantAuthorizationdate'=>date('Ymd')//查征授权时间(为授权书签章时间），格式为YYYYMMDD
            // 'grantAuthorizationdate'=>'20230325'//查征授权时间(为授权书签章时间），格式为YYYYMMDD
        );
        // dd($user);
        $jsonData = json_encode($user);
        $signString = self::encrypt($jsonData,$key);


        $sign = strtoupper(md5('secretKey='.$key.'&data='.$signString.'&timestamp='.date('Y-m-d H:i:s')));

        $data = array(
            'data' => $signString, //签名域
        );
        // dd($data);

        $paramstring = json_encode($data);
        // dd($paramstring);
        $content = self::buerCurl($url,$sign,$paramstring);
        // dd($content);
        $result = json_decode($content,true);  //返回结果
        // dd($result);

        // $res = self::getInvestData2($requestId,$scoreNo);
        $result['data']['requestId'] = $requestId;
        $result['data']['scoreNo'] = $scoreNo;
        return $result;
    }
    /**
     * 获取征信结果
     */
    static public function getInvestData2($requestId,$scoreNo){
        // $key = "67333FCC2FA244F8BEE4613AC18CD845";   //密钥-测试环境
        $key = "81A2F363DC5D4429BB6A0B8DFDD95C3E";   //密钥-正式环境

        // $url = "https://server.junxinhengyi.cn:16633/api/guarantee/querysdkresult"; //测试
        $url = "https://serice.junxinhengyi.cn:4433/api/guarantee/querysdkresult"; //线上
        $user = array(
            'requestId'=>$requestId, //请求流水号，单次http请求唯一
            'scoreNo'=>$scoreNo, // 请求编号
        );

        $jsonData = json_encode($user);
        $signString = self::encrypt($jsonData,$key);

        $sign = strtoupper(md5('secretKey='.$key.'&data='.$signString.'&timestamp='.date('Y-m-d H:i:s')));
        $data = array(
            'data' => $signString, //签名域
        );
        // dd($data);

        $paramstring = json_encode($data);
        // dd($paramstring);
        $content = self::buerCurl($url,$sign,$paramstring);
        // dd($content);
        $result = json_decode($content,true);  //返回结果
        // dd($result);
        $result['requestId'] = $requestId;
        $result['scoreNo'] = $scoreNo;
        return $result;

    }

    /**
     * 上报征信-申请担保
     */
    static public function applyInvestData($input,$ocr){
        // $key = "C2811D4EE95E4835A327F11E21CA3382";   //密钥-测试环境
        $key = "FA4F1CB125684F3285B836D0613006FC";   //密钥-正式环境

        // $url = "https://server.junxinhengyi.cn:16633/api/guarantee/v2/applyGuarantee"; //测试
        $url = "https://serice.junxinhengyi.cn:4433/api/guarantee/v2/applyGuarantee"; //线上


        $ocrFrontImg = '/2023/'.$input['idcard_front'];

        $ocrBackImg = '/2023/'.$input['idcard_back'];


        $creditAuthorizationAtt = '/2023/'.$input['pact_url_2'];

        $signedAuthorizationAtt = '/2023/'.$input['pact_url_3'];

        $userinfo = [
            "name"=>$input['cert_name'],//姓名
            "idcardNumber"=>$input['cert_no'],//身份证号
            "mobile"=>$input['mobile'], //手机号码
            "homeAddress"=>$input['address'], //家庭地址
            "resiStatus"=>9, //居住状态  9未知
            "resiPc"=>$ocr['resiPc'],//居住地邮编
            "resiDist"=>$input['rid'],//居住地行政区划
            "homeTel"=>$input['mobile'],//住宅电话
            "registerDist"=>$input['rid'],//户籍所在地行政区划（市县大区号）
            "ocrFrontImg"=>$ocrFrontImg,//身份证ocr正面图片 --ocr手动输入信息
            "ocrBackImg"=>$ocrBackImg,//身份证ocr反面图片
            "ocrName"=>$input['cert_name'], //ocr结果中的姓名
            "ocrStartValidDate"=>$ocr['ocrStart'],//ocr结果中的身份证有效期开始日期
            "ocrEndValidDate"=>$ocr['ocrEnd'],//ocr结果中的身份证有效期结束日期(长期填2099-12-31)
            "ocrAddress"=>$ocr['ocrAddress'],//OCR结果中的地址，户籍地址
            "ocrSex"=>$input['gender']=='男'?1:2,//OCR结果中的性别 1男2女
            "ocrNation"=>$ocr['ocrNation'],//OCR结果中的民族
            "ocrIssueOrg"=>$ocr['ocrIssueOrg'], //OCR结果中的发证机关
            "creditAuthorizationAtt"=>$creditAuthorizationAtt,//征信授权书pdf附件地址
            "signedAuthorizationAtt"=>$signedAuthorizationAtt, //签字签章授权书pdf附件地址-用户授权协议
            "firstContactInfo"=>[

            ],
            "secondContactInfo"=>[

            ]
        ];
        $eduInfo = [
            "eduLevel"=>99, //学历 * 10-研究生* 20-本科* 30-大专* 40-中专、职高、技校* 60-高中* 91-初中及以下* 99-未知
            "acaDegree"=>9 //学位* 1-名誉博士* 2-博士* 3-硕士* 4-学士* 对于没有“学位”的，统一填写“5-无”；* 9-未知
        ];
        $mariInfo = [
            "marriStatus"=>99,
        ];
        $career = [
            "empStatus"=>99,
            "cpnName"=>"",
            "cpnType"=>99,
            "industry"=>"9",
            "cpnAddr"=>"浙江省温州市瑞安市",
            "occupation"=>"Z",
            "title"=>9,
            "techTitle"=>9,
        ];
        $loanInfo = [
            "loanNo"=>$input['trade_no'], //贷款订单号
            "loanMoney"=>$input['rent_total'], //贷款金额-总租金
            "periodNum"=>$input['month_total'], //贷款期限-总期数
            "periodUnit"=>2, //贷款期限类型1：天 2：月
            "repayType"=>3, //还款方式1：先息后本2：等额本金3：等额本息
            "loanUse"=>"数码租赁", //贷款用途
            "annualInterestRate"=>0, //贷款年利率  总租金/12/成本
            "loanStartDate"=>date('Y-m-d H:i:s',$input['begin_time']), //借款期限起始日yyyy-MM-dd HH:mm:ss
            "loanEndDate"=>date('Y-m-d H:i:s',$input['end_time']), //借款期限结束日yyyy-MM-dd HH:mm:ss
            "productType"=>7
        ];
        $guaranteeInfo = [
            "coverCharge"=>"0", //服务费
            "coverChargeRatio"=>"0", //服务费比率
            "guaranteeAgreementId"=>$input['trade_no'], //借款合同编号，乙方与贷款人之间的合同
            "partner"=>"瑞安市诺明网络科技有限公司",
            "guaranteeRate"=>"0.01%", //担保费率
            "guaranteeFee"=> sprintf('%.2f',$input['rent_total']*0.0001), //担保费率*总租金
            "website"=>"都来租", //平台
            "payMoney"=>sprintf('%.2f',$input['rent_total']/$input['month_total']), //每期租金
            "buyoutPriceMoney"=>$input['setmeal_price'], //买断金
            "totalRent"=>$input['rent_total'],//总租金
            "shareRatio"=>'1%' //担保份额
        ];
        $guaranteeLetterInfo = [

        ];
        $guaranteePeriodFee = [

        ];
        $user = array(
            'userInfo'=>$userinfo,
            'eduInfo'=>$eduInfo,
            'mariInfo'=>$mariInfo,
            'career'=>$career,
            'loanInfo'=>$loanInfo,
            'guaranteeInfo'=>$guaranteeInfo,
            'guaranteeLetterInfo'=>$guaranteeLetterInfo,
            'guaranteePeriodFee'=>$guaranteePeriodFee
        );

        $jsonData = json_encode($user);
        $signString = self::encrypt($jsonData,$key);

        $sign = strtoupper(md5('secretKey='.$key.'&data='.$signString.'&timestamp='.date('Y-m-d H:i:s')));
        $data = array(
            'data' => $signString, //签名域
        );
        // dd($data);

        $paramstring = json_encode($data);
        // dd($paramstring);
        $content = self::buerCurl1($url,$sign,$paramstring);
        // dd($content);
        $result = json_decode($content,true);  //返回结果
        // dd($result);
        return $result;
        /*
        array:4 [
          "code" => "0"
          "msg" => "成功"
          "data" => array:1 [
            "platformLoanNo" => "G20230324112548000004"
          ]
          "result" => true
        ]
        */
    }
    /**
     * 上报征信-担保放款
     */
    static public function remitInvestData($input,$repayPlanInfoList){


        // $key = "C2811D4EE95E4835A327F11E21CA3382";   //密钥-测试环境
        $key = "FA4F1CB125684F3285B836D0613006FC";   //密钥-正式环境

        // $url = "https://server.junxinhengyi.cn:16633/api/guarantee/v2/remit"; //测试
        $url = "https://serice.junxinhengyi.cn:4433/api/guarantee/v2/remit"; //线上
        /*
        $repayPlanInfoList = [
                [
                  'needRepayAmount'=>1000, //应还款总额
                  'needRepayCapital'=>1000, //应还本金
                  'period'=>1, //还款期数
                  'repayDate'=>"2022-09-01 14:00:01" //还款日期
                ],
                [
                  'needRepayAmount'=>1000,
                  'needRepayCapital'=>1000,
                  'period'=>2,
                  'repayDate'=>"2022-09-01 14:00:01"
                ],
                [
                  'needRepayAmount'=>1000,
                  'needRepayCapital'=>1000,
                  'period'=>3,
                  'repayDate'=>"2022-09-01 14:00:01"
                ],
                [
                  'needRepayAmount'=>1000,
                  'needRepayCapital'=>1000,
                  'period'=>4,
                  'repayDate'=>"2022-09-01 14:00:01"
                ],
                [
                  'needRepayAmount'=>1000,
                  'needRepayCapital'=>1000,
                  'period'=>5,
                  'repayDate'=>"2022-09-01 14:00:01"
                ]

            ];
            */
        $user = array(
            'platformLoanNo'=>$input['platformLoanNo'], //申请担保接口返回的担保平台单号
            'loanAgreementId'=>$input['trade_no'], //订单ID
            'remitTime'=>date('Y-m-d H:i:s'), //放款日期
            'loanStartDate'=>date('Y-m-d H:i:s',$input['begin_time']), //借款期限起始日
            'loanEndDate'=>date('Y-m-d H:i:s',$input['end_time']),//借款期限结束日
            // 'guarType'=>1,
            // 'reguarType'=>'',
            // 'certType'=>'',
            // 'certNo'=>'11111',
            'periodNum'=>$input['month_total'],//还款计划期数
            'repayPlanInfoList'=>$repayPlanInfoList //还款计划
        );

        $jsonData = json_encode($user);
        $signString = self::encrypt($jsonData,$key);

        $sign = strtoupper(md5('secretKey='.$key.'&data='.$signString.'&timestamp='.date('Y-m-d H:i:s')));
        $data = array(
            'data' => $signString, //签名域
        );
        // dd($data);

        $paramstring = json_encode($data);
        // dd($paramstring);
        $content = self::buerCurl1($url,$sign,$paramstring);
        // dd($content);
        $result = json_decode($content,true);  //返回结果
        // dd($result);
        return $result;


    }
    /**
     * 上报征信-还款
     */
    static public function repayInvestData($input){


        // $key = "C2811D4EE95E4835A327F11E21CA3382";   //密钥-测试环境
        $key = "FA4F1CB125684F3285B836D0613006FC";   //密钥-正式环境

        // $url = "https://server.junxinhengyi.cn:16633/api/guarantee/v2/repay"; //测试
        $url = "https://serice.junxinhengyi.cn:4433/api/guarantee/v2/repay"; //线上

        $user = array(
            'platformLoanNo'=>$input['platformLoanNo'], //申请担保接口返回的担保平台单号
            'period'=>$input['which_period'], //租期
            'amount'=>$input['rent'],//还款金额
            'repayDate'=>date('Y-m-d H:i:s'), //还款日期
        );

        $jsonData = json_encode($user);
        $signString = self::encrypt($jsonData,$key);

        $sign = strtoupper(md5('secretKey='.$key.'&data='.$signString.'&timestamp='.date('Y-m-d H:i:s')));
        $data = array(
            'data' => $signString, //签名域
        );
        // dd($data);

        $paramstring = json_encode($data);
        // dd($paramstring);
        $content = self::buerCurl1($url,$sign,$paramstring);
        // dd($content);
        $result = json_decode($content,true);  //返回结果
        // dd($result);
        return $result;

    }
    /**
     * 上报征信-逾期还款
     */
    static public function overdueRepayInvestData($input){


        // $key = "C2811D4EE95E4835A327F11E21CA3382";   //密钥-测试环境
        $key = "FA4F1CB125684F3285B836D0613006FC";   //密钥-正式环境

        // $url = "https://server.junxinhengyi.cn:16633/api/guarantee/v2/overdueRepay"; //测试
        $url = "https://serice.junxinhengyi.cn:4433/api/guarantee/v2/overdueRepay"; //线上

        $user = array(
            'platformLoanNo'=>$input['platformLoanNo'], //申请担保接口返回的担保平台单号
            'period'=>$input['which_period'], //租期
            'amount'=>$input['rent'],//还款金额
            'repayDate'=>date('Y-m-d H:i:s'), //还款日期
        );

        $jsonData = json_encode($user);
        $signString = self::encrypt($jsonData,$key);

        $sign = strtoupper(md5('secretKey='.$key.'&data='.$signString.'&timestamp='.date('Y-m-d H:i:s')));
        $data = array(
            'data' => $signString, //签名域
        );
        // dd($data);

        $paramstring = json_encode($data);
        // dd($paramstring);
        $content = self::buerCurl1($url,$sign,$paramstring);
        // dd($content);
        $result = json_decode($content,true);  //返回结果
        // dd($result);
        return $result;

    }
    /**
     * 上报征信-结清
     */
    static public function settleInvestData($input){


        // $key = "C2811D4EE95E4835A327F11E21CA3382";   //密钥-测试环境
        $key = "FA4F1CB125684F3285B836D0613006FC";   //密钥-正式环境

        // $url = "https://server.junxinhengyi.cn:16633/api/guarantee/v2/settle"; //测试
        $url = "https://serice.junxinhengyi.cn:4433/api/guarantee/v2/settle"; //线上

        $user = array(
            'platformLoanNo'=>$input['platformLoanNo'], //申请担保接口返回的担保平台单号
            'initCredName'=>'瑞安市诺明网络科技有限公司',//初始债权人名称（资金方全称），催收总金额大于0时必填
            'initCredOrgNum'=>'91330381MAC65FWH5X',//初始债权人名称（资金方全称），催收总金额大于0时必填
            'compensatoryMoney'=>$input['compensatoryMoney'], //催收总金额=在保期限内的（代偿总本金额-代偿还款总本金额）+未还利息(可为未还正常利息+未缴罚息等),未还金额
            'origDbtCate'=>"9",//原债务种类(催收总金额大于0时必填)
            "initRpySts"=>0,//债务转移时的还款状态（若有代偿，此数据为必须）对于资产处置业务，填写该笔债务的初始债权人转让债权时，债务人的还款状态；对于垫款业务，填写发生垫款时债务人的履约状态。
            'fivecate'=>2,//五级分类
        );

        $jsonData = json_encode($user);
        $signString = self::encrypt($jsonData,$key);

        $sign = strtoupper(md5('secretKey='.$key.'&data='.$signString.'&timestamp='.date('Y-m-d H:i:s')));
        $data = array(
            'data' => $signString, //签名域
        );
        // dd($data);

        $paramstring = json_encode($data);
        // dd($paramstring);
        $content = self::buerCurl1($url,$sign,$paramstring);
        // dd($content);
        $result = json_decode($content,true);  //返回结果
        // dd($result);
        return $result;

    }
    /**
     * 上报征信-追偿
     */
    static public function dunRepayInvestData($input){

        // $key = "C2811D4EE95E4835A327F11E21CA3382";   //密钥-测试环境
        $key = "FA4F1CB125684F3285B836D0613006FC";   //密钥-正式环境

        // $url = "https://server.junxinhengyi.cn:16633/api/guarantee/v2/dunRepay"; //测试
        $url = "https://serice.junxinhengyi.cn:4433/api/guarantee/v2/dunRepay"; //线上

        $user = array(
            'platformLoanNo'=>$input['platformLoanNo'], //申请担保接口返回的担保平台单号
            'surplusAmount'=>$input['surplusAmount'], //当前追偿后剩余金额
            'amount'=>$input['amount'],//追偿本金额
            'dunDate'=>$input['dunDate'], //追偿日期
            "fivecate"=>"2"
        );

        $jsonData = json_encode($user);
        $signString = self::encrypt($jsonData,$key);

        $sign = strtoupper(md5('secretKey='.$key.'&data='.$signString.'&timestamp='.date('Y-m-d H:i:s')));
        $data = array(
            'data' => $signString, //签名域
        );
        // dd($data);

        $paramstring = json_encode($data);
        // dd($paramstring);
        $content = self::buerCurl1($url,$sign,$paramstring);
        // dd($content);
        $result = json_decode($content,true);  //返回结果
        // dd($result);
        return $result;

    }

    /**
     * 上报征信-追偿结清
     */
    static public function dunSettleInvestData($input){


        // $key = "C2811D4EE95E4835A327F11E21CA3382";   //密钥-测试环境
        $key = "FA4F1CB125684F3285B836D0613006FC";   //密钥-正式环境

        // $url = "https://server.junxinhengyi.cn:16633/api/guarantee/v2/dunSettle"; //测试
        $url = "https://serice.junxinhengyi.cn:4433/api/guarantee/v2/dunSettle"; //线上

        $user = array(
            'platformLoanNo'=>$input['platformLoanNo'], //申请担保接口返回的担保平台单号
            'settleDate'=>$input['settleDate'], //追偿日期
            "fivecate"=>"2"
        );

        $jsonData = json_encode($user);
        $signString = self::encrypt($jsonData,$key);

        $sign = strtoupper(md5('secretKey='.$key.'&data='.$signString.'&timestamp='.date('Y-m-d H:i:s')));
        $data = array(
            'data' => $signString, //签名域
        );
        // dd($data);

        $paramstring = json_encode($data);
        // dd($paramstring);
        $content = self::buerCurl1($url,$sign,$paramstring);
        // dd($content);
        $result = json_decode($content,true);  //返回结果
        // dd($result);
        return $result;

    }

    /**
     * 上报征信-合同重新发送请求
     */
    static public function agreementInvestData($input){


        // $key = "C2811D4EE95E4835A327F11E21CA3382";   //密钥-测试环境
        $key = "FA4F1CB125684F3285B836D0613006FC";   //密钥-正式环境

        // $url = "https://server.junxinhengyi.cn:16633/api/guarantee/v2/agreement"; //测试
        $url = "https://serice.junxinhengyi.cn:4433/api/guarantee/v2/agreement"; //线上

        $user = array(
            'platformLoanNo'=>$input['platformLoanNo'], //申请担保接口返回的担保平台单号
            'agreementType'=>"2", //合同类型：2委托担保合同；1保函
        );

        $jsonData = json_encode($user);
        $signString = self::encrypt($jsonData,$key);

        $sign = strtoupper(md5('secretKey='.$key.'&data='.$signString.'&timestamp='.date('Y-m-d H:i:s')));
        $data = array(
            'data' => $signString, //签名域
        );
        // dd($data);

        $paramstring = json_encode($data);
        // dd($paramstring);
        $content = self::buerCurl1($url,$sign,$paramstring);
        // dd($content);
        $result = json_decode($content,true);  //返回结果
        // dd($result);
        return $result;

    }

    /**
     * 请求接口返回内容 -查询
     * @param  string $url [请求的URL地址]
     * @param  string $params [请求的参数]
     * @param  int $ipost [是否采用POST形式]
     * @return  string
     */
    static private function buerCurl($url,$sign,$data=null){
        $curl = curl_init();
        curl_setopt($curl,CURLOPT_URL,$url);
        curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,FALSE);
        curl_setopt($curl,CURLOPT_SSL_VERIFYHOST,FALSE);
        if(!empty($data)){
            curl_setopt($curl,CURLOPT_POST,1);
            curl_setopt($curl,CURLOPT_POSTFIELDS,$data);
        }
        curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);
        //下面这行是修改后增加的代码，就是配置设置host访问，发送的数据类型为application/json
        curl_setopt($curl, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json',
            // 'G_APP_ID:785ee257-a27c-4396-a0cf-61b18bb79c22', //APPID-测试
            'G_APP_ID:da41c54b-6468-4fc2-9f8b-997d0e387800', //APPID-正式
            'G_TIMESTAMP:'.date('Y-m-d H:i:s'), //拼接签名原始数据时用的时间戳
            'G_SIGN:'.$sign, //第2步生成的签名
            // 'G_INVEST_ID:327' //资金方身份id-测试
            'G_INVEST_ID:308' //资金方身份id-正式328
        ));
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }

    /**
     * 请求接口返回内容-上报
     * @param  string $url [请求的URL地址]
     * @param  string $params [请求的参数]
     * @param  int $ipost [是否采用POST形式]
     * @return  string
     */
    static private function buerCurl1($url,$sign,$data=null){
        $curl = curl_init();
        curl_setopt($curl,CURLOPT_URL,$url);
        curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,FALSE);
        curl_setopt($curl,CURLOPT_SSL_VERIFYHOST,FALSE);
        if(!empty($data)){
            curl_setopt($curl,CURLOPT_POST,1);
            curl_setopt($curl,CURLOPT_POSTFIELDS,$data);
        }
        curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);
        //下面这行是修改后增加的代码，就是配置设置host访问，发送的数据类型为application/json
        curl_setopt($curl, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json',
            // 'G_APP_ID:1bcdc403-16fe-4550-bdaa-ee5e920656d4', //APPID-测试
            'G_APP_ID:b870b2ab-ee94-4845-bc94-b1d36a0441c7', //APPID-正式
            'G_TIMESTAMP:'.date('Y-m-d H:i:s'), //拼接签名原始数据时用的时间戳
            'G_SIGN:'.$sign, //第2步生成的签名
            // 'G_INVEST_ID:327' //资金方身份id-测试
            'G_INVEST_ID:308' //资金方身份id-正式308
        ));
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }

    /**
     * 加密字符串 AES
     * @param string $encrypt 字符串
     * @param string $key     加密key 16位
     * @return string
     */
    static public function encrypt( $encrypt, $key ) {

        // $base_encrypt = base64_encode($encrypt);
        $key = substr(openssl_digest(openssl_digest($key, 'sha1', true), 'sha1', true), 0, 16);

        $data = openssl_encrypt($encrypt, 'AES-128-ECB', $key, OPENSSL_RAW_DATA);

        $data = strtoupper(bin2hex($data));

        return $data;
    }


    //上传sftp
    static public function login($username, $password,$local_file, $remote_file)
    {
        $methods = array(
          'hostkex' => 'ssh-rsa,ssh-dss',
          'client_to_server' => array(
            'crypt' => 'aes256-ctr,aes192-ctr,aes128-ctr, aes256-cbc,aes192-cbc,aes128-cbc ,3des-cbc,blowfish-cbc',
            'comp' => 'none'),
          'server_to_client' => array(
            'crypt' => 'aes256-ctr,aes192-ctr,aes128-ctr,aes256-cbc,aes192-cbc,aes128-cbc,3des-cbc,blowfish-cbc',
            'comp' => 'none'));
        // $callbacks = array('disconnect' => 'my_ssh_disconnect');
        $connection = ssh2_connect('124.114.235.10', 33333,$methods);
        // dd($connection);
        if (! ssh2_auth_password($connection, $username, $password))
//            throw new Exception("Could not authenticate with username $username " .
//                                "and password $password.");
        $sftp = ssh2_sftp($connection);
        // dd($sftp);
        // copy($local_file,"ssh2.sftp://{$sftp}" . $remote_file);
        $stream = fopen("ssh2.sftp://{$sftp}" . $remote_file,'w+');

        if (! $stream)
           // throw new Exception("Could not open file: $remote_file");

        $data_to_send = file_get_contents($local_file);
        if ($data_to_send === false)
          //  throw new Exception("Could not open local file: $local_file.");

        if (fwrite($stream, $data_to_send) === false)
         //   throw new Exception("Could not send data from file: $local_file.");

        fclose($stream);
        return '上传成功';
    }



}
